package 二叉树相关问题.层次遍历;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层平均值 {

    List<Double> list = new ArrayList<>();
    public List<Double> averageOfLevels(TreeNode root) {
        List<List<Double>> lists = new LinkedList<>();
        if (root==null)
            return list;
        Queue<TreeNode> q=new LinkedList();
        q.offer(root);
        while (!q.isEmpty()){
            List<Double>  integers= new ArrayList<>();
            for (int i = q.size(); i>0 ; i--) {
                TreeNode poll = q.poll();
                integers.add((double) poll.val);
                if(poll.left!=null)
                    q.offer(poll.left);
                if (poll.right!=null)
                    q.offer(poll.right);
            }
            lists.add(new ArrayList<>(integers));
        }
        for (List<Double> integers : lists) {
            list.add(average(integers));
        }
        return list;
    }
    //求平均值
    public double average(List<Double> integers){
        double sum=0;
        for (int i = 0; i < integers.size(); i++) {
            sum+=integers.get(i);
        }
        return sum/integers.size();
    }
}
